#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

const int WRITE_SIZE = 0x400;
const int SEND_SIZE = 0x400;
const int CROSS_SIZE = 2;

const std::string file_prefix = "./file/";

struct sockaddr_in server;
int sock;

uint16_t serverport = 0;
std::string serverip;

static void usage(std::string proc)
{
    std::cout << "\nUsage:" << proc << " serverIp serverPort\n" << std::endl;
}

bool process(FILE* r_fp, FILE* w_fp)
{
    char send_buf[SEND_SIZE];
    char rece_buf[WRITE_SIZE];
    memset(send_buf, 0, sizeof send_buf);
    memset(rece_buf, 0, sizeof rece_buf);
    if (!fgets(send_buf, CROSS_SIZE, r_fp)) return false;
    sendto(sock, send_buf, strlen(send_buf), 0, (struct sockaddr*)&server, sizeof server);
    struct sockaddr_in temp;
    socklen_t len = sizeof temp;
    auto s = recvfrom(sock, rece_buf, sizeof rece_buf, 0, (struct sockaddr*)&temp, &len);
    if (s > 0) {
        printf("%s", rece_buf);
        fprintf(w_fp, "%s", rece_buf);
    }
    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 3) {
        usage(argv[0]);
        exit(1);
    }

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
        std::cerr << "socket error." << std::endl;
        exit(2);
    }

    serverport = atoi(argv[2]);
    serverip = argv[1];
    memset(&server, 0, sizeof server);
    server.sin_family = AF_INET;
    server.sin_port = htons(atoi(argv[2]));
    server.sin_addr.s_addr = inet_addr(argv[1]);
    
    auto fp_a1 = fopen((file_prefix + "A1").c_str(), "r");
    auto fp_a2 = fopen((file_prefix + "A2").c_str(), "r");
    auto fp_b1 = fopen((file_prefix + "B1").c_str(), "w");
    auto fp_b2 = fopen((file_prefix + "B2").c_str(), "w");

    if (!fp_a1 || !fp_a2 || !fp_b1 || !fp_b2) {
        std::cerr << "open file error." << std::endl;
        exit(2);
    }

    bool finished1 = false, finished2 = false, flag = false;
    while (!finished1 || !finished2) {
        if (flag) {
            if (!process(fp_a1, fp_b1)) finished1 = true;
        } 
        else {
            if (!process(fp_a2, fp_b2)) finished2 = true;
        } 
        flag = !flag;
    }
    return 0;
}

